import { useState, useEffect, useRef } from "react";
import { ScrollView, View, Text } from "@tarojs/components";
import style from "./index.scss";
import NoData from "../NoData";
import { useDidHide, useDidShow } from "@tarojs/taro";

export default (props) => {
  const {
    getList,
    params,
    row,
    pageSize = 10,
    list,
    setList,
    isReverse = false,
    topRender,
  } = props;
  const [defaultList, setDefaultList] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [HasNextPage, setHasNextPage] = useState(true);
  const [loading, setLoading] = useState(false);

  const ref = useRef();

  const isFirst = useRef(true);

  // useDidShow(() => {
  //   ref.current = null;
  // });

  useDidShow(() => {
    if (isFirst.current) {
      getListData(1);
    }
    isFirst.current = false;
  });

  useEffect(() => {
    if (
      isFirst.current == false &&
      JSON.stringify(params) !== JSON.stringify(ref.current)
    ) {
      getListData(1);
      setPageNumber(1);
      setList ? setList([]) : setDefaultList([]);
      ref.current = params;
    }
  }, [params]);

  useEffect(() => {
    if (pageNumber && pageNumber !== 1) {
      getListData(pageNumber);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageNumber]);

  const getListData = (page) => {
    setHasNextPage(false);
    setLoading(true);

    // 去掉 null 跟 undefined 字段
    const obj =
      typeof params === "object"
        ? Object.keys(params).reduce((acc, key) => {
            const val = params[key];
            if (val === null || val === undefined) {
              return acc;
            }

            return {
              ...acc,
              [key]: val,
            };
          }, {})
        : params;

    getList &&
      getList({
        pageNo: page.toString(),
        pageSize: pageSize.toString(),
        ...obj,
      })
        .then((res) => {
          console.log(res, "----");
          if (res) {
            const resList = res.data || [];
            if (isReverse) {
              resList.reverse();
            }
            setList
              ? setList(
                  page === 1
                    ? res.data || []
                    : (list || defaultList).concat(resList || [])
                )
              : setDefaultList(
                  page === 1
                    ? res.data || []
                    : (list || defaultList).concat(resList || [])
                );
            setHasNextPage(res.totalnum > pageSize * page);
          }
          setLoading(false);
          // setHasNextPage(true)
        })
        .catch((err) => {
          setLoading(false);
        });
  };

  const PageLoadMore = () => {
    // 页面上拉加载更多
    if (HasNextPage) {
      setPageNumber((n) => n + 1);
    }
  };

  return (
    <View className={style.visitorListWarp}>
      <ScrollView
        className={style.scrollView}
        scroll-y
        onscrolltolower={PageLoadMore}
      >
        {topRender && topRender}
        {!loading && (list || defaultList)?.length === 0 ? (
          <NoData></NoData>
        ) : (
          <View className={style.visitorListContent}>
            <View className={style.visitorList}>
              {(list || defaultList).map(
                (item, index) => row && row(item, index)
              )}
            </View>

            {/* bottom */}
            <View className={style.pageBottom}>
              <Text>
                {loading ? "加载中..." : HasNextPage ? "加载完成" : ""}
              </Text>
            </View>
          </View>
        )}
      </ScrollView>
    </View>
  );
};
